package com.taotao.st3.sharding5.ext.kengen;


import com.baidu.fsg.uid.UidGenerator;
import org.apache.shardingsphere.infra.algorithm.core.context.AlgorithmSQLContext;
import org.apache.shardingsphere.infra.algorithm.keygen.core.KeyGenerateAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

import java.util.Collection;
import java.util.HashSet;
import java.util.Properties;
import java.util.Set;

/**
 * <p>
 *  百度UidGenerator
 * </p>
 *
 * @author fanbeibei
 * @version 1.0.0
 * @date 2023/4/12 14:51
 */
public class BaiduUid implements KeyGenerateAlgorithm {


    private Properties props;

    private UidGenerator uidGenerator;


    @Lazy
    @Autowired
    public BaiduUid(UidGenerator uidGenerator) {
        this.uidGenerator = uidGenerator;
    }

    @Override
    public void init(final Properties props) {
        this.props = props;
    }


    @Override
    public String getType() {
        return "uidGenerator";
    }

    @Override
    public Collection<Object> getTypeAliases() {
        return KeyGenerateAlgorithm.super.getTypeAliases();
    }

    @Override
    public boolean isDefault() {
        return true;
    }


    @Override
    public Collection<? extends Comparable<?>> generateKeys(AlgorithmSQLContext context, int keyGenerateCount) {
        Set<Long> idList = new HashSet<>(keyGenerateCount);

        for (int i = 0; i < keyGenerateCount; i++) {
            // 这里是从本地缓存里取id，所以不会有性能问题
            idList.add(uidGenerator.getUID());
        }

        return idList;
    }

    @Override
    public boolean isSupportAutoIncrement() {
        return false;
    }
}
